#include "friendmodel.h"
#include "mysql.h"
using namespace ChatRoom;
// 添加好友关系
bool FriendModel::insertf(int userid, int friendid) {
    MySQL mysql;//创建一个连接对象
    if (mysql.Connect()) {//是否连接到了数据库
        char sql[1024] = { 0 };
        sprintf(sql, "insert into friend (userid, friendid) values (%d, %d)", userid, friendid);
        if (mysql.Query(sql) == nullptr) {//这个函数用来执行SQL语句
            return false;
        }
       
        //有两个sprintf语句应该分开写，防止混淆
        sprintf(sql, "INSERT INTO friend (userid, friendid) VALUES (%d, %d)", friendid, userid);
        if (mysql.Query(sql) == nullptr) {//返回空指针，函数返回false
            return false;
        }

        
    }
    else
        return false;
}
// 返回用户好友列表
vector<User> FriendModel::query(int userid)
{
    // 1.组装sql语句
    char sql[1024] = { 0 };

    sprintf(sql, "select a.id,a.name,a.state from user a inner join friend b on b.friendid = a.id where b.userid=%d", userid);

    vector<User> vec;
    MySQL mysql;
    if (mysql.Connect())
    {
        MYSQL_RES* res = mysql.Query(sql);
        if (res != nullptr)
        {
            // 把userid用户的所有好友放入vec中返回
            MYSQL_ROW row;
            while ((row = mysql_fetch_row(res)) != nullptr)
            {
                User user;
                user.setId(atoi(row[0]));
                user.setName(row[1]);
                user.setState(row[2]);
                vec.push_back(user);
            }
            mysql_free_result(res);
            return vec;
        }
    }
    return vec;
}

//删除好友
bool FriendModel::deletef(int userid, int friendid) {
    //组装SQL语句
    MySQL mysql;
    char sql[1024] = { 0 };
    if (mysql.Connect()) {

        sprintf(sql, "delete from friend  where userid = %d and friendid = %d", userid, friendid);
        if (mysql.Query(sql) == nullptr) {
            return false;
        }

        sprintf(sql, "delete from friend  where userid = %d and friendid = %d", friendid, userid);
        if (mysql.Query(sql) == nullptr) {
            return false;
        }
        return true;
    }
    else
        return false;

}
//统计好友个数
int FriendModel::fnumber(int userid) {
    int count = -1;
    MySQL mysql;
    char sql[1024] = { 0 };
    if (mysql.Connect()) {
        sprintf(sql, "select count(*) from friend where userid=%d", userid);//用于统计查询结果集中匹配条件的行数
        MYSQL_RES* res = mysql.Query(sql);//把查询结果保存在MYSQL_RES*类型的 res指向的内存的结构体中
        if (res != nullptr)//如果这个指针不空
        {
            MYSQL_ROW row;//
            if ((row = mysql_fetch_row(res)) != nullptr)
            {
                count = atoi(row[0]);
            }
            mysql_free_result(res);
        }
    }
    return count;
}